package cn.tom.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

//授权服务器
// /oauth2/token
// /oauth2/check_token  这两个端点暴露出来
@Configuration
@EnableAuthorizationServer  //这是个过滤器，要激活
public class QqAuth2ServerConfig extends
        AuthorizationServerConfigurerAdapter {
    //身份验证管理
    @Autowired
    AuthenticationManager authenticationManagerBean;
    //是那个用户明细
    @Autowired
    UserDetailsService userDetailsService;
    //密码比对的方式
    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        System.out.println("checkTokenAccess(\"permitAll()\")");
        oauthServer.tokenKeyAccess("permitAll()")//在过滤器 放行 /oauth/token 端点路径
                .checkTokenAccess("permitAll()") //allow check token
                .allowFormAuthenticationForClients();
    }

    /**
     * 配置哪些 client_id client_secret
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        System.out.println("configure(ClientDetailsServiceConfigurer clients)");

        clients.inMemory()
                .withClient("guoji").secret(passwordEncoder.encode("223344"))
                .authorizedGrantTypes("password", "authorization_code",
                        "client_credentials", "implicit", "refresh_token")
                .scopes("all")
                .autoApprove(true)
                .redirectUris("http://www.baidu.com");   // 认证成功重定向URL

    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        System.out.println("configure(AuthorizationServerEndpointsConfigurer endpoints)");
        endpoints.authenticationManager(authenticationManagerBean)
                .userDetailsService(userDetailsService);
    }
}

